package com.kylin.module.shop.actions;

import java.text.SimpleDateFormat;
import java.util.LinkedList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;
import org.hibernate.criterion.Order;

import com.kylin.common.Constants;
import com.kylin.common.dict.orm.Dict;
import com.kylin.common.entity.MsgKey;
import com.kylin.common.exception.BusinessException;
import com.kylin.common.paginate.DisplayPage;
import com.kylin.common.paginate.PageManager;
import com.kylin.hibernate.BaseHibernateDAO;
import com.kylin.hibernate.CriteriaInfo;
import com.kylin.hibernate.PropertyCondition;
import com.kylin.module.shop.business.ContentBlogic;
import com.kylin.module.shop.forms.ContentForm;
import com.kylin.module.shop.forms.TradeForm;
import com.kylin.module.shop.orm.Company;
import com.kylin.module.shop.orm.Content;
import com.kylin.struts.BaseDispatchAction;

public class ManageContentAction extends BaseDispatchAction  {

	protected static Logger log = Logger.getLogger(ManageContentAction.class);
	int pageSize = 10;// 分页列表的每页行数  

	public ActionForward add(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) {
		log.info("添加贸易信息 : "+request.getParameter("title"));
		String forward = "add";
		ContentBlogic blogic = new ContentBlogic();
		try {
			ContentForm form = (ContentForm)actionForm;
			Company com = (Company)request.getSession().getAttribute(Constants.CURR_LANG_COMPANY);
			if(com == null)
				throw new BusinessException("已超时或尚未登录，请登录后操作");
			form.setCompany(com);
			form.setCreatedby(com.getUser().getUsername());
			blogic.addContent(form);
			log.debug("添加贸易信息成功" + form.getTitle());
			// 返回成功的信息，需要在结果页面添加 <mytag:MyActionMsg />
	        request.setAttribute(Constants.MSGKEY, new MsgKey("","添加贸易信息成功"));
		}catch (Exception e) {
			forward = doException( request, e, forward);
		}
		return mapping.findForward(forward);
	}
	
	/**
	 * 贸易信息查看列表
	 * @param mapping
	 * @param actionForm
	 * @param request
	 * @param response
	 * @return
	 */
	public ActionForward manageContentList(ActionMapping mapping, ActionForm actionForm,
			HttpServletRequest request, HttpServletResponse response) {
		log.debug("贸易信息查看列表 : " + request.getParameter("type"));
		String forward = "manageContentList";
		int pageNum = 1;
		String searchId = request.getParameter("searchId");
		CriteriaInfo cinfo = null;

		try {
			if (request.getParameter("page") != null) {
				pageNum = Integer.parseInt(request.getParameter("page"));
			}
			if (searchId == null) {//第一次查询，没有searchId（查询号）
				
				/*********构造查询条件***********/
				List conditions = new LinkedList(); //先创建个容器准备装条件
				String type = request.getParameter("type");
				if(type!= null && !type.equals("")){  //输入了查询条件：类别
					PropertyCondition cond = new PropertyCondition("type", new Short(type),PropertyCondition.OPERATOR_EQ );
					conditions.add(cond);
				}
				
				String title = request.getParameter("title");
				if(title!= null && !title.equals("")){  //输入了查询条件：类别
					PropertyCondition cond = new PropertyCondition("title", "%"+title+"%",PropertyCondition.OPERATOR_LIKE );
					conditions.add(cond);
				}
				Company com = (Company)request.getSession().getAttribute(Constants.CURR_LANG_COMPANY); 				
				PropertyCondition cond2 = new PropertyCondition("company", com,PropertyCondition.OPERATOR_EQ );
				conditions.add(cond2);
				// 增加其他条件参照以上
				/***************************/
				
				cinfo = new CriteriaInfo(Content.class, conditions);
				cinfo.setOrderby(Order.desc("createdon"));
				addUserCacheCriteriaInfo(request, cinfo);
			} else {
				cinfo = getUserCacheCriteriaInfo(request, searchId);
			}
			DisplayPage page = PageManager.getDisplayPage(pageSize, pageNum, cinfo);
			request.setAttribute(Constants.KEY_REQUEST_RESULT, page);
		} catch (Exception e) {
			// 参数传入 forward ，
			// 发生BusinessException异常后的结果页面和成功的页面相同，
			//通过页面的<mytag:MyActionMsg/>显示错误
			// 发生其它严重错误，则跳转到错误页，需要配置中定义<forward name="SystemException"
			// path="/common/errorPage.jsp" />
			doException(request, e, forward);
		}
		System.out.print("\nforward="+forward);
		return mapping.findForward(forward);
	}

	/**
	 * 查看修改贸易信息
	 * @param mapping
	 * @param actionForm
	 * @param request
	 * @param response
	 * @return
	 */
	public ActionForward bfUpdate(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) {
		log.debug("查看修改贸易信息 : "+request.getParameter("id"));
		String forward = "editPage";
		ContentBlogic blogic = new ContentBlogic();
		try {
			Content cont = blogic.getContent(request.getParameter("id"));
			request.setAttribute(Constants.KEY_REQUEST_RESULT,cont);
			ContentForm form = (ContentForm)actionForm;
			form.setId(cont.getId());
			form.setType(cont.getType());
			form.setAddress(cont.getAddress());
			form.setContact(cont.getContact());
			form.setContent(cont.getContent());
			form.setTitle(cont.getTitle());
			form.setCountry(cont.getCountry());
			if(cont.getCatproduct() != null)
				form.setCatProductId(cont.getCatproduct().getId());
			if(cont.getUnit() != null)
				form.setUnit(cont.getUnit().getId());
			if(cont.getCurrency() != null)
				form.setCurrency(cont.getCurrency().getId());
			if(cont.getDuedate() != null){
				SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
				form.setDuedate(format.format(cont.getDuedate()));
			}
			form.setPrice(cont.getPrice());
			form.setQuantity(cont.getQuantity());
			form.setCountry(cont.getCountry());
			
			form.setFax(cont.getFax());
			form.setFaxArea(cont.getFaxArea());
			form.setFaxCountry(cont.getFaxCountry());
			form.setPhone(cont.getPhone());
			form.setPhoneArea(cont.getPhoneArea());
			form.setPhoneCountry(cont.getPhoneCountry());
			form.setPostcode(cont.getPostcode());
			form.setEmail(cont.getEmail());
			form.setPpackage(cont.getPpackage());
		}catch (Exception e) {
			forward = doException( request, e, forward);
		}
		return mapping.findForward(forward);
	}

	public ActionForward delete(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) {
		log.info("删除贸易信息 : "+request.getParameter("id"));
		String forward = "manageContentList";
		ContentBlogic blogic = new ContentBlogic();
		try {
			blogic.deleteContent(new Long(request.getParameter("id")));
			log.debug("删除贸易信息成功ok" );
			// 返回成功的显示信息，需要在结果页面添加 <mytag:MyActionMsg />
	        request.setAttribute(Constants.MSGKEY, new MsgKey(" ","删除贸易信息成功"));
		}catch (Exception e) {
			forward = doException( request, e, forward);
		}
		try {
	        CriteriaInfo cinfo = getUserCacheCriteriaInfo(request, request.getParameter("searchId"));
			DisplayPage page = PageManager.getDisplayPage(pageSize, Integer.parseInt(request.getParameter("page")), cinfo);
			//  返回列表
			request.setAttribute(Constants.KEY_REQUEST_RESULT, page);        
		} catch (BusinessException e) {
		}
		return mapping.findForward(forward);
	}

	public ActionForward update(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) {
		log.info("修改贸易信息 : "+request.getParameter("name"));
		String forward = "editPage";
		ContentBlogic blogic = new ContentBlogic();
		try {
			ContentForm form = (ContentForm)actionForm;
			Content obj = blogic.updateContent(form);
			log.debug("修改贸易信息成功: " + form.getTitle());
			// 返回成功的信息，需要在结果页面添加 <mytag:MyActionMsg />
	        request.setAttribute(Constants.MSGKEY, new MsgKey("","修改贸易信息成功"));
	        request.setAttribute(Constants.KEY_REQUEST_RESULT, obj);  
		}catch (Exception e) {
			forward = doException( request, e, forward);
		}
		return mapping.findForward(forward);
	}
	/**
	 * 从后台添加出售和收购信息
	 * @param mapping
	 * @param actionForm
	 * @param request
	 * @param response
	 * @return
	 */
	public ActionForward tradeAdd(ActionMapping mapping,ActionForm actionForm,HttpServletRequest request,HttpServletResponse response)
	{
		log.debug("从后台添加供求信息"+request.getParameter("title"));
		String forward = "tradeAddSucc";
		TradeForm form = (TradeForm)actionForm;
		try
		{
			ContentBlogic logic = new ContentBlogic();
			logic.addTrade(form);
			request.setAttribute(Constants.MSGKEY,new MsgKey("","添加信息成功"));
			if("tradeList".equals(request.getParameter("nextdo")))
			{
				return this.manageTradeList(mapping, actionForm, request, response);
			}
		}catch(Exception e)
		{
			doException(request,e,forward);
		}
		return mapping.findForward(forward);
	}
	/**
	 * 从后台删除出售和收购信息
	 * @param mapping
	 * @param actionForm
	 * @param request
	 * @param response
	 * @return
	 */
	public ActionForward tradeDelete(ActionMapping mapping,ActionForm actionForm,HttpServletRequest request,HttpServletResponse response)
	{
		String id = request.getParameter("id");
		log.debug("删除贸易信息"+id);
		try
		{
			ContentBlogic logic = new ContentBlogic();
			logic.deleteContent(new Long(id));
			request.setAttribute(Constants.MSGKEY, new MsgKey(" ","删除贸易信息成功"));
		}catch(Exception e)
		{
			log.error(e);
			e.printStackTrace();
		}
		return this.manageTradeList(mapping, actionForm, request, response);
	}
	/**
	 * 根据id查看详细贸易信息
	 * @param mapping
	 * @param actionForm
	 * @param request
	 * @param response
	 * @return
	 */
	public ActionForward tradeDetail(ActionMapping mapping,ActionForm actionForm,HttpServletRequest request,HttpServletResponse response)
	{
		String id = request.getParameter("id");
		log.debug("查看贸易详细信息"+id);
		String forward = "tradeDetail";
		try
		{
			ContentBlogic logic = new ContentBlogic();
			Content trade = logic.getContent(id);
			request.setAttribute(Constants.KEY_REQUEST_RESULT,trade);
		}catch(Exception e)
		{
			doException(request,e,forward);
		}
		return mapping.findForward(forward);
	}
	/**
	 * 查询后台出售和收购信息
	 * @param mapping
	 * @param actionForm
	 * @param request
	 * @param response
	 * @return
	 */
	public ActionForward manageTradeList(ActionMapping mapping,ActionForm actionForm,HttpServletRequest request,HttpServletResponse response)
	{
		log.debug("查询后台添加贸易信息列表");
		int pageNum = 1;
		String forward = "tradeList";
		String searchId = request.getParameter("searchId");
		CriteriaInfo cinfo = null;
		try
		{
			if(request.getParameter("page") != null)
			{
				pageNum = Integer.parseInt(request.getParameter("page"));
			}
			if(searchId == null)
			{
				List conditions = new LinkedList();
				String type = request.getParameter("keyword_type");
				if(type!= null && !type.equals("")){  //输入了查询条件：类别
					PropertyCondition cond = new PropertyCondition("type", new Short(type),PropertyCondition.OPERATOR_EQ );
					conditions.add(cond);
				}
				
				String title = request.getParameter("keyword_title");
				if(title!= null && !title.equals("")){  //输入了查询条件：标题
					PropertyCondition cond = new PropertyCondition("title", "%"+title+"%",PropertyCondition.OPERATOR_LIKE );
					conditions.add(cond);
				}
								
				if(hasParam(request.getParameter("keyword_username")))
				{
					String username = request.getParameter("keyword_username");
					conditions.add(new PropertyCondition("company.user.username","%"+username+"%",PropertyCondition.OPERATOR_LIKE));
				}
				
				if( hasParam(request.getParameter("catproduct")))
				{
					String catid = request.getParameter("catproduct");
				    conditions.add(new PropertyCondition("catProduct.id",new Long(catid),PropertyCondition.OPERATOR_EQ ));
				}
				
				String language = request.getParameter("language");
				if(language!=null && !language.equals("")){ //输入了查询条件：语言
					PropertyCondition cond = new PropertyCondition("language",language,PropertyCondition.OPERATOR_EQ);
					conditions.add(cond);
				}
				
				String country = request.getParameter("keyword_country");
				if(country!=null && !country.equals("")){ //输入了查询条件：国家
					PropertyCondition cond = new PropertyCondition("country",country,PropertyCondition.OPERATOR_EQ);
					conditions.add(cond);
				}
				cinfo = new CriteriaInfo(Content.class, conditions);
				cinfo.setOrderby(Order.desc("createdon"));
				addUserCacheCriteriaInfo(request, cinfo);
			} else {
				cinfo = getUserCacheCriteriaInfo(request, searchId);
			}
			DisplayPage page = PageManager.getDisplayPage(pageSize, pageNum, cinfo);
			request.setAttribute(Constants.KEY_REQUEST_RESULT, page);
		}catch(Exception e)
		{
			doException(request,e,forward);
		}
		return mapping.findForward(forward);
	}


}

